#!/usr/bin/env python3
import subprocess
import sys
import os
import shutil

def check_python_version():
    """检查Python版本是否满足要求"""
    required_version = (3, 6)
    current_version = sys.version_info[:2]
    if current_version < required_version:
        print(f"错误: 需要Python {required_version[0]}.{required_version[1]}或更高版本")
        return False
    print(f"Python版本检查通过: {sys.version.split()[0]}")
    return True

def check_adb():
    """检查adb是否可用"""
    if shutil.which('adb') is None:
        print("错误: 未找到adb命令")
        print("请确保Android SDK Platform Tools已安装且已添加到PATH中")
        return False
    
    try:
        result = subprocess.run(['adb', 'version'], capture_output=True, text=True)
        if result.returncode == 0:
            print(f"ADB版本检查通过: {result.stdout.split()[4]}")
            return True
    except Exception as e:
        print(f"检查ADB时出错: {e}")
    return False

def check_device_connection():
    """检查是否有Android设备连接"""
    try:
        result = subprocess.run(['adb', 'devices'], capture_output=True, text=True)
        devices = [line for line in result.stdout.split('\n')[1:] if line.strip()]
        if devices:
            print(f"检测到{len(devices)}个设备:")
            for device in devices:
                print(f"  - {device}")
            return True
        else:
            print("错误: 未检测到已连接的Android设备")
            return False
    except Exception as e:
        print(f"检查设备连接时出错: {e}")
        return False

def check_app_installed():
    """检查测试应用是否已安装"""
    try:
        result = subprocess.run(
            ['adb', 'shell', 'pm', 'list', 'packages', 'com.example.voicealarm'],
            capture_output=True,
            text=True
        )
        if 'com.example.voicealarm' in result.stdout:
            print("应用已安装")
            return True
        else:
            print("警告: 测试应用未安装")
            return False
    except Exception as e:
        print(f"检查应用安装状态时出错: {e}")
        return False

def verify_app_permissions():
    """验证应用权限"""
    permissions = [
        'android.permission.SCHEDULE_EXACT_ALARM',
        'android.permission.RECORD_AUDIO',
        'android.permission.VIBRATE'
    ]
    
    try:
        for permission in permissions:
            result = subprocess.run(
                ['adb', 'shell', 'pm', 'list', 'permissions', '|', 'grep', permission],
                capture_output=True,
                text=True
            )
            if permission in result.stdout:
                print(f"权限检查通过: {permission}")
            else:
                print(f"警告: 未找到权限 {permission}")
    except Exception as e:
        print(f"检查权限时出错: {e}")

def create_test_directory():
    """创建测试结果目录"""
    test_dir = "test_results"
    if not os.path.exists(test_dir):
        os.makedirs(test_dir)
        print(f"创建测试结果目录: {test_dir}")
    else:
        print(f"测试结果目录已存在: {test_dir}")

def main():
    print("开始环境检查...")
    print("-" * 50)
    
    checks = [
        ("Python版本检查", check_python_version),
        ("ADB可用性检查", check_adb),
        ("设备连接检查", check_device_connection),
        ("应用安装检查", check_app_installed)
    ]
    
    all_passed = True
    for check_name, check_func in checks:
        print(f"\n执行检查: {check_name}")
        if not check_func():
            all_passed = False
    
    print("\n检查应用权限...")
    verify_app_permissions()
    
    print("\n准备测试环境...")
    create_test_directory()
    
    print("\n" + "-" * 50)
    if all_passed:
        print("环境检查完成，所有必要条件均已满足")
        print("你可以开始运行自动化测试了：python automated_tests.py")
    else:
        print("环境检查完成，但存在一些问题需要解决")
        print("请解决上述问题后再运行测试")

if __name__ == "__main__":
    main()
